/**
 * Created by bjh on 2017/11/04.
 */

import React, { Component } from "react";
import "../index.less"
import GM from "g2-mobile";
import PropTypes from "prop-types";

class Tooltip extends Component{
	constructor(props, context){
		super(props);
		this.showData = []
		this.title = "";
		this.state = {
			id: "tooltip" + Math.random(100),
			show: false, //是否显示
			left: 0, top: 0, //显示位置
		};
		// chart图的宽高
		this.width = 0;
		this.height = 0;
	}

	componentDidMount(){
		this.bind(this.props.chart, this.props.data);
		this.getCanvas();
	}

	bind(chart, data){
		if (chart instanceof GM.Chart !== true || data instanceof Array !== true){
			throw new Error("this tooltip was inited by a wrong way, try to send a chart instance and array data!")
		}
		if (this.chart){
			console.warn("this tooltip has been used!");
			return false;
		}
		this.chart = chart;
		this.data = data;
		return true;
	}

	unbind(chart){
		if(this.chart === chart){
			this.chart = null;
		}
	}

	showTooltip(x, y, data){
		this.showData = data
		this.setState({
			show: true,
			left: x,
			top: y,
        })
	}

	closeTooltip(){
		this.setState({
			show: false
		})
	}

	getPoint(canvas, x, y) {  
		let bbox = canvas.getBoundingClientRect();
		this.width = bbox.width;
		this.height = bbox.height;
		return {  
			x: x - bbox.left,   
			y: y - bbox.top 
		};  
	} 

	getCanvas(){  
		console.log(this.chart)
		let canvas = document.getElementById(this.chart._attrs.id);  
		//处理点击事件显示tooltips
		canvas.onclick = (event) => {  
			let point = this.getPoint(canvas, event.clientX, event.clientY)  
			let x = parseInt(point.x);  
			let y = parseInt(point.y);  
			// 根据画布坐标获取对应数据集
			let data = this.chart.getSnapRecords(point);
			this.showTooltip(x, y, data);
		}  
	}

	formatStyle(){
		//根据点击位置 靠左或者靠右显示
		let divStyle = {};
		const { left, top, show } = this.state;
		const { margin } = this.props;
		if( left <= this.width / 2){
			divStyle = { 
				position: "absolute",
				visibility: show ? "visible" : "hidden",
				top: top, 
				left: left,
			}
		} else {
			let leftW = left - document.getElementById(this.state.id).clientWidth
			divStyle = { 
				position: "absolute",
				visibility: show ? "visible" : "hidden",
				top: top, 
				left: leftW,
			}
		}
		return divStyle;
	}

	render(){
		const divStyle = this.formatStyle();
		return (
			<div 
				id={this.state.id}
				className={`ac-tooltip ${ this.state.show ? "" : "display-none" }`}
				style={divStyle}>
				<h4 className="ac-title"></h4>
				<ul className="ac-list">
				{
					this.showData.map((item, i)=>{
						return(
							<li key={ item.yAxisData + i }>
								<span style={{ color: "#D6EAFE" }}>{item.name}</span> : {item.yAxisData}
							</li>
						)
					})
				}
				</ul>
			</div>
		)
	}
}

Tooltip.propTypes = {
	data: PropTypes.array,
	chart: PropTypes.object,
	margin: PropTypes.array,
};

export default Tooltip